package xyz.xiezc.spider.prase;

import lombok.extern.slf4j.Slf4j;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import xyz.xiezc.ioc.annotation.Component;
import xyz.xiezc.spider.common.Request;
import xyz.xiezc.spider.common.Response;
import xyz.xiezc.spider.common.XBean;
import xyz.xiezc.spider.common.XUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author wb-xzc291800
 * @date 2019/04/18 17:41
 */
@Slf4j
@Component
public class PhotoInfoHtmlParseImpl implements ParseResponse {


    /**
     * 图片详情正则
     */
    Pattern detailPattern = Pattern.compile("https://www.mzitu.com/\\d+?(/\\d+)?");
    /**
     * 匹配规则图片链接的正则
     */
    Pattern commonUrlPattern = Pattern.compile("https://i.meizitu.net/\\d{4}/\\d{2}/\\d{2}[a-z]{1}(\\d{2})\\.jpg");
    /**
     * 匹配图片详情的正则.为了获取最大的图片url
     */
    Pattern detailPatternLast = Pattern.compile("https://www.mzitu.com/\\d+?/(\\d+?)");

    @Override
    public  XBean parse(XBean xBean)  {
        dealParsePhotoInfo(xBean);
        return xBean;
    }

    private  void dealParsePhotoInfo(XBean xBean) {
        Request request = xBean.getRequest();
        String url = request.getUrl();
        Matcher matcher = detailPattern.matcher(url);
        if (matcher.matches()) {
            Response response = xBean.getResponse();
            Document document = XUtil.getDocument(response);
            Elements select = document.select("body > div.main > div.content > div.main-image > p > a > img");
            String href = select.attr("src");

            Map<String, Object> extra = request.getExtra();

            Request request1 = new Request();
            request1.setUrl(XUtil.getComplieUrl(href, request));
            request1.addExtra(extra);

            //标题
            String title = document.select("body > div.main > div.content > h2").text();
            request1.addExtra("title", title);
            //显示的时间
            String showTime = document.select("body > div.main > div.content > div.main-meta > span:nth-child(2)").text();
            request1.addExtra("showTime", showTime.replaceAll("发布于 ", ""));
            // type 分类
            String type=  document.select("body > div.main > div.content > div.main-meta > span:nth-child(1)").text();
            request1.addExtra("type", type .replaceAll("分类：", ""));
            //标签
            Elements tagEles = document.select("body > div.main > div.content > div.main-tags > a");
            List<String> tags = tagEles.stream()
                    .map(element -> element.text())
                    .collect(Collectors.toList());
            request1.addExtra("tags", tags);
            xBean.addNextRequest(request1);

            //判断图片是否符合规则, 如果符合规则就直接构造后面的链接
            Matcher matcher1 = commonUrlPattern.matcher(request1.getUrl());
            Elements select1 = document.select("body > div.main > div.content > div.pagenavi > a");
            if (matcher1.matches()) {
                List<Request> urls = createUrls(select1, request1, matcher1);
                xBean.addNextRequest(urls);
            } else {
                Element last = select1.last();
                if (last.text().startsWith("下一")) {
                    select1.remove(last);
                }
                Element first = select.first();
                if (first.text().startsWith("上一")) {
                    select1.remove(first);
                }

                select1.forEach(element -> {
                    String newUrl = XUtil.getComplieUrl(element.attr("href"), request);
                    Request request2 = new Request();
                    request2.setUrl(newUrl);
                    request2.setExtra(extra);
                    xBean.addNextRequest(request2);
                });
            }
            xBean.setStatus(3);
        }
    }

    /**
     * @param select1  图片详情页下面的页码的a标签列表
     * @param request  第一张图片的request
     * @param matcher1 正则匹配的第一张照片的正则
     */
    private List<Request> createUrls(Elements select1, Request request, Matcher matcher1) {
        String href = request.getUrl();
        Map<String, Object> extra = request.getExtra();
        AtomicInteger lastUrlIndex = new AtomicInteger(1);
        select1.stream().forEach(element -> {
            String href1 = element.attr("href");
            Matcher matcher2 = detailPatternLast.matcher(href1);
            if (matcher2.matches()) {
                String group = matcher2.group(1);
                if (group != null) {
                    Integer pageNo = Integer.valueOf(group);
                    if (lastUrlIndex.get() < pageNo) {
                        lastUrlIndex.set(pageNo);
                    }
                }
            }
        });
        //根据规则构建链接
        int lastUrlCount = lastUrlIndex.get();
        List<Request> nextRequest = new ArrayList<>(lastUrlCount);
        if (lastUrlCount > 1) {
            String group = matcher1.group(1);
            String prefix = href.substring(0, href.lastIndexOf(group));
            for (int i = 1; i < lastUrlCount; i++) {
                String s = "";
                if (i + 1 < 10) {
                    s = "0" + Objects.toString(i + 1);
                } else {
                    s = Objects.toString(i + 1);
                }
                String nextUrl = prefix + s + ".jpg";
                Request request2 = new Request();
                request2.setUrl(nextUrl);
                request2.setExtra(extra);
                nextRequest.add(request2);
            }
        }
        return nextRequest;
    }
}
